package com.xbongbong.paas.model.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.dao.PaasFormDao;
import com.xbongbong.paas.domain.entity.FormNumForOneApplicationEntity;
import com.xbongbong.paas.domain.entity.OneFormMaxListTypeNumEntity;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormRefEntity;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.BIProductReformEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasFormRefModel;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.CoOpPermsAddDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.WorkReportSetDao;
import com.xbongbong.saas.domain.entity.WorkReportSetEntity;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WorkReportTypeEnum;
import com.xbongbong.sys.model.DepartmentModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: wufeng
 * @date: 2018/8/13 15:22
 * @desrcption: PaaS主表单实现类
 */
@Service("paasFormModel")
public class PaasFormModelImpl implements PaasFormModel {

    private static final String COLUMNS = " id, corpid, app_id, menu_id, name, name_en, enable, saas_mark, business_type, is_process_form, verify_rule, disable_field_assign, front_cache, title_type, custom_title, summary, labels, association_list, surcharge, price_association, business_rules, co_op_perms, permission, creator_id, add_time, update_time, del, field_position, distributor_mark, hidden ";


    @Resource
    private PaasFormDao paasFormDao;
    @Resource
    private WorkReportSetDao workReportSetDao;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private PaasFormRefModel paasFormRefModel;
    @Resource
    private PaasAppModel paasAppModel;

    @Override
    public Integer insert(PaasFormEntity entity) {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        if (Objects.isNull(entity.getSort())) {
            // 避免sort为空，插入报错
            entity.setSort(0);
        }
        return paasFormDao.insert(entity);
    }

    @Override
    public List<PaasFormEntity> insertBatch(List<PaasFormEntity> list) {
        list.forEach(item->{
            if (Objects.isNull(item.getSort())) {
                // 避免sort为空，插入报错
                item.setSort(0);
            }
        });
        paasFormDao.insertBatch(list);
        return list;
    }

    @Override
    public List<PaasFormEntity> updateBatch(List<PaasFormEntity> list, String corpid) {
        paasFormDao.updateBatch(list, corpid);
        return list;
    }

    @Override
    public List<PaasFormEntityExt> initBatch(List<PaasFormEntityExt> list, String corpid) {
        list.forEach(item->{
            if (Objects.isNull(item.getSort())) {
                // 避免sort为空，插入报错
                item.setSort(0);
            }
        });
        paasFormDao.initBatch(list, corpid);
        return list;
    }

    @Override
    public List<PaasFormEntityExt> list(Map<String, Object> map) {
        map.put("columns", new StringBuffer(COLUMNS).append(", co_op_perms as co_op_perms_ext"));
        map.put("orderByStr","menu_id,sort");
        return paasFormDao.findEntitys(map);
    }

    @Override
    public List<PaasFormEntityExt> findEntitys(Map<String, Object> entity) {
        return paasFormDao.findEntitys(entity);
    }

    @Override
    public List<PaasFormEntity> findEntity(Map<String, Object> entity) {
        return paasFormDao.findEntity(entity);
    }

    @Override
    public PaasFormEntityExt getByKey(Long key, String corpid) {
        return paasFormDao.getByKey(key, corpid);
    }

    @Override
    public PaasFormEntityExt getByKeyIncludeDel(Long key, String corpid) {
        return paasFormDao.getByKeyIncludeDel(key, corpid);
    }

    @Override
    public PaasFormEntityExt getByMenuId(Long key, String corpid) {
        return paasFormDao.getByMenuId(key, corpid);
    }

    @Override
    public PaasFormEntityExt getByMenuIdAndBusinessType(Integer key, String corpid, Integer businessType) {
        return paasFormDao.getByMenuIdAndBusinessType(key, corpid, businessType);
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> map) {
        return paasFormDao.getEntitysCount(map);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }

    @Override
    public Integer delete(Long key, String corpid) {
        return  paasFormDao.deleteByKey(key, corpid);
    }

    @Override
    public Integer update(PaasFormEntity entity) {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        return paasFormDao.update(entity);
    }

    @Override
    public Integer updateName(PaasFormEntity entity) {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        return paasFormDao.updateName(entity);
    }

    @Override
    public List<PaasFormEntityExt> userFormList(Map<String, Object> map) {
        map.put("columns", new StringBuffer(COLUMNS).append(", co_op_perms as co_op_perms_ext"));
        return paasFormDao.userFormList(map);
    }

    @Override
    public Integer updateCustomTitle(PaasFormEntity entity) {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        return paasFormDao.updateCustomTitle(entity);
    }

    @Override
    public Integer deleteByMenuId(PaasFormEntity paasFormEntity) {
        return  paasFormDao.deleteByMenuId(paasFormEntity.getMenuId(), paasFormEntity.getCorpid());
    }

    @Override
    public List<PaasFormEntityExt> getEnableFormList(String corpid, Integer businessType) {
        return getEnableFormList(corpid, businessType, null);
    }

    @Override
    public List<PaasFormEntityExt> getEnableFormList(String corpid, Integer businessType, String columns) {
        Map<String,Object> map = new HashMap<>();
        map.put("corpid", corpid);
        map.put("businessType", businessType);
        map.put("columns", columns);
        map.put("del", 0);
        map.put("enable",1);
        return findEntitys(map);
    }

    @Override
    public List<PaasFormEntityExt> getEnableFormListDistributor(String corpid, Integer businessType, Integer distributorMark) {
        Map<String,Object> map = new HashMap<>();
        //  map.put("appId", appId);
        map.put("corpid", corpid);
        map.put("businessType", businessType);
        map.put("del", 0);
        map.put("enable",1);
        map.put("distributorMark",distributorMark);
        //map.put("distributorMark", 0);
        return list(map);
    }


    @Override
    public List<PaasFormEntityExt> getFormListDistributor(String corpid, Integer businessType, Integer distributorMark) {
        Map<String,Object> map = new HashMap<>();
        map.put("corpid", corpid);
        map.put("businessType", businessType);
        map.put("del", 0);
        map.put("distributorMark",distributorMark);
        return list(map);
    }


    @Override
    public Integer updateDistribution(Long key, String corpid, Integer openDistribution) {
        return paasFormDao.updateDistribution(key, corpid, openDistribution);
    }

    @Override
    public PaasFormEntityExt getByBusinessType(Integer businessType, String corpid) {
        return paasFormDao.getByBusinessType(businessType,corpid,null);
    }

    @Override
    public PaasFormEntityExt getByBusinessType4Distributor(Integer businessType, String corpid, Integer distributor, String columns) {
        if (Objects.isNull(distributor)) {
            distributor = DistributorMarkEnum.OTHER.getCode();
        }
        return paasFormDao.getByBusinessType4Distributor(businessType,corpid, distributor,columns);
    }

    @Override
    public List<Long> getFormIdList4Distributor(Integer businessType, String corpid, Integer distributor) {
        return paasFormDao.getFormIdList4Distributor(businessType,corpid, distributor);
    }

    @Override
    public PaasFormEntityExt getByBusinessType(Integer businessType, String corpid , String columns) {
        return paasFormDao.getByBusinessType(businessType,corpid,columns);
    }

    @Override
    public List<PaasFormEntityExt> getByBusinessTypes(Map<String, Object> param) {
        return paasFormDao.getByBusinessTypes(param);
    }

    @Override
    public FormNumForOneApplicationEntity getOneApplicationMaxFormTypeNum(String corpid) {
        return paasFormDao.getOneApplicationMaxFormTypeNum(corpid);
    }

    @Override
    public OneFormMaxListTypeNumEntity getOneFormMaxListTypeNum(String corpid) {
        return paasFormDao.getOneFormMaxListTypeNum(corpid);
    }

    /**
     * 根据业务类型查询没有钉钉待办模板的表单信息
     * @param map
     * @return
     */
    @Override
    public List<PaasFormEntityExt> getFormWithoutProcessCodeByBusinessType(Map<String, Object> map) {
        return paasFormDao.getFormWithoutProcessCodeByBusinessType(map);
    }

    @Override
    public List<PaasFormEntityExt> getEnableList(String corpid) {
        Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("corpid", corpid);
        map.put("del", DelEnum.NORMAL.getDel());
        map.put("enable",BasicConstant.IS_USE);
        return list(map);
    }

    @Override
    public Integer updateBatchTemp(List<PaasFormEntityExt> list) throws XbbException {
        return paasFormDao.updateBatchTemp(list);
    }

    @Override
    public void batchUpdateDel(Integer del, Integer updateTime, List<Long> idIn, String corpid) {
        paasFormDao.batchUpdateDel(del,updateTime,idIn,corpid);
    }

    /**
     * 批量更新业务规则(主要是镜像用来把business_rules改为1)
     * @param list
     * @param corpid
     * @param businessRules
     * @author xingxing.xiao
     */
    @Override
    public Integer updateBusinessRuleBatch(List<Long> list, String corpid, String businessRules) {
        return paasFormDao.updateBusinessRuleBatch(list, corpid, businessRules);
    }

    /**
     * 批量删除
     * @param list 主键id集合
     * @param corpid
     * @author xingxing.xiao
     */
    @Override
    public Integer deleteBatch(List<Long> list, String corpid) {
        return paasFormDao.deleteBatch(list, corpid);
    }

    @Override
    public Long getFormIdByBusinessType(String corpid, int businessType) {
        return paasFormDao.getFormIdByBusinessType(corpid,businessType);
    }

    @Override
    public PaasFormEntityExt getByBusinessTypeNoEnable(int businessType, String corpid) {
        return paasFormDao.getByBusinessTypeNoEnable(businessType,corpid);
    }

    @Override
    public Integer deleteBatchByMenuId(List<Long> list, String corpid) {
        return paasFormDao.deleteBatchByMenuId(list, corpid);
    }

    @Override
    public PaasFormEntity getByFormId(Long formId, String corpid) {
        return paasFormDao.getByFormId(formId, corpid);
    }

    @Override
    public List<PaasFormEntityExt> getEnableFormList(String corpid, List<Integer> businessTypes) {
        Map<String,Object> map = new HashMap<>();
        //  map.put("appId", appId);
        map.put("corpid", corpid);
        map.put("businessTypes", businessTypes);
        map.put("del", 0);
        map.put("enable",1);
        //map.put("distributorMark", 0);
        return list(map);
    }

    @Override
    public List<PaasFormEntityExt> getByIdIn(Set<Long> formIds, String corpid) {
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("idIn", formIds);
        param.put("del", 0);
        return findEntitys(param);
    }

    @Override
    public List<PaasFormEntityExt> getWorkReportTemplateWithPermission(String corpid, UserVO loginUser, Long appId, Object o) {

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Integer> enableWorkReportBusinessTypeList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 工作报告模板是否启用
        List<Integer> workReportTypeList = Arrays.asList(WorkReportTypeEnum.DAILY.getType(),WorkReportTypeEnum.WEEKLY.getType(),WorkReportTypeEnum.MONTHLY.getType());
        param.clear();
        param.put(StringConstant.CORPID, corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("enable",1);
        param.put("typeIn",workReportTypeList);
        List<WorkReportSetEntity> workReportSetEntities = workReportSetDao.findEntitys(param);
        if (Objects.nonNull(workReportSetEntities) && workReportSetEntities.size() != 0){
            for (int i = 0; i < workReportSetEntities.size(); i++) {
                WorkReportSetEntity workReportSetEntity = workReportSetEntities.get(i);
                Integer type = workReportSetEntity.getType();
                switch (type){
                    case 1:
                        enableWorkReportBusinessTypeList.add(XbbRefTypeEnum.WORKREPORT_DAILY.getCode());
                        break;
                    case 2:
                        enableWorkReportBusinessTypeList.add(XbbRefTypeEnum.WORKREPORT_WEEKLY.getCode());
                        break;
                    case 3:
                        enableWorkReportBusinessTypeList.add(XbbRefTypeEnum.WORKREPORT_MONTHLY.getCode());
                        break;
                    default:
                        break;
                }
            }
        }
        param.clear();
        param.put(StringConstant.CORPID, corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("saasMark", SaasMarkEnum.SAAS.getCode());
        param.put("businessTypeList", enableWorkReportBusinessTypeList);
        param.put("enable",1);
        List<PaasFormEntityExt> workReportPassFormList = getByBusinessTypes(param);
        return workReportPassFormList;
    }


    @Override
    public void removeByPermission(List<PaasFormEntityExt> paasFormEntityList, UserVO loginUser) {
        Iterator<PaasFormEntityExt> it = paasFormEntityList.iterator();
        while(it.hasNext()) {
            PaasFormEntityExt paasFormEntityExt = it.next();

            if (!validatePermission(paasFormEntityExt, loginUser)){
                it.remove();
            }
        }
    }


    @Override
    public void validateByPermission(PaasFormEntityExt paasFormEntityExt, UserVO loginUser) throws XbbException {
        if (Objects.isNull(paasFormEntityExt)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        if (!RedundantTemplateTypeEnum.isMultiTemplate(paasFormEntityExt.getBusinessType())) {
            return;
        }
        if ( Objects.equals(paasFormEntityExt.getEnable(), 0) || Objects.equals(paasFormEntityExt.getDel(), 1) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
        }
        if ( !validatePermission(paasFormEntityExt, loginUser) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
        }
    }

    /**
     * 校验当前用户使用有使用表单的权限
     * @param paasFormEntityExt
     * @param loginUser
     * @return false：无表单使用权限，true：有表单使用权限
     */
    private boolean validatePermission(PaasFormEntityExt paasFormEntityExt, UserVO loginUser) {
        List<OptionalRangeEntity> permissionList = null;
        try {
            permissionList = JSON.parseArray(paasFormEntityExt.getPermission(),
                    OptionalRangeEntity.class);
        } catch (Exception e) {

        }
        return getPermission(permissionList, loginUser);
    }

    @Override
    public boolean getPermission(List<OptionalRangeEntity> permissionList, UserVO loginUser) {
        permissionList = permissionList == null ? new ArrayList<>() : permissionList;
        if (permissionList.isEmpty()) {
            return true ;
        }
        //是否包含在规则中
        boolean flag = false;
        List<Long> depIdSet = new ArrayList<>();
        for (OptionalRangeEntity optionalRangeEntity : permissionList) {
            String property = optionalRangeEntity.getProperty();
            String id = optionalRangeEntity.getId();

            if (Objects.equals(property, OptionalRangeEnum.DEPT.getValue())){
                //部门判断,先将所有部门id置入depIdSet，再获取所有子部门判断
                Long departmentId = StringUtil.StringToLong(id, -1L);
                depIdSet.add(departmentId);
                continue;
            } else if (Objects.equals(property, OptionalRangeEnum.ROLE.getValue())){
                //角色判断
                String roleIds = loginUser.getRoleIds();
                String roleId = "|" + id + "|";
                //所属角色在设置角色中
                if (roleIds.indexOf(roleId) > -1) {
                    flag = true;
                    break;
                }
            } else if (Objects.equals(property, OptionalRangeEnum.USER.getValue())){
                //员工判断
                String userId = loginUser.getUserId();
                //所属用户在设置用户中
                if (Objects.equals(userId, id)) {
                    flag = true;
                    break;
                }
            }
        }

        String department = loginUser.getDepartment();
        List<Long> departmentIdList = JSON.parseArray(department, Long.class);

        //所有有权限的部门
        List<Long> allDepIdList = new ArrayList<>();
        List<Long> subDepIdList = departmentModel.getSubDepIdList(loginUser.getCorpid(), depIdSet);
        allDepIdList.addAll(subDepIdList);
        allDepIdList.addAll(depIdSet);

        //与用户所属部门取交集
        allDepIdList.retainAll(departmentIdList);
        if (!allDepIdList.isEmpty()) {
            flag = true;
        }
        return flag;
    }
    @Override
    public List<PaasFormEntity> getNameByKeys(List<Long> formIdList, String corpid) {
        return paasFormDao.getNameByKeys(formIdList,corpid);
    }

    /**
     * 获取子产品插入的表单列表
     *
     * @param mainBusinessFormList 主业务列表
     * @param allBusinessTypes 有产品子表单的主业务类型
     */
    @Override
    public void insertSubProductFormList(List<PaasFormEntity> mainBusinessFormList, Set<Integer> allBusinessTypes) {
        List<PaasFormEntity> shouldInsertFormList = new ArrayList<>();
        //主业务formId和主业务businessType的对应关系map，为啥不在paasFormEntity中存一个参数，
        Map<Long, Integer> mainFormIdAndBusinessMap = new HashMap<>(mainBusinessFormList.size() * 2);

        //查询出一个产品app的id的集合
        Set<String> corpidSet = mainBusinessFormList.stream().map(e -> e.getCorpid()).collect(Collectors.toSet());
        Map<String, Object> appMap = new HashMap<>();
        appMap.put("corpidIn", corpidSet);
        appMap.put("del", BasicConstant.ZERO);
        appMap.put("enable", BasicConstant.ONE);
        appMap.put("alias", "product");
        List<PaasAppEntity> paasAppEntities = paasAppModel.findEntitys(appMap);
        Map<String, Long> appCorpidMap = paasAppEntities.stream().collect(Collectors.toMap(PaasAppEntity::getCorpid, PaasAppEntity::getId,
                (key1, key2)->key2));
        for (PaasFormEntity paasFormEntity : mainBusinessFormList) {
            String corpid = paasFormEntity.getCorpid();
            if (Objects.isNull(appCorpidMap.get(corpid))) {
                //这边是因为本地数据库发现没有产品应用，兼容一下脏数据
                continue;
            }
            mainFormIdAndBusinessMap.put(paasFormEntity.getId(), paasFormEntity.getBusinessType());
            Integer mainBuesineesType = paasFormEntity.getBusinessType();
            if (allBusinessTypes.contains(mainBuesineesType)) {
                //判断一个主业务是不是有多个产品，有几个产品就需要生成几个产品子表单
                List<BIProductReformEnum> biProductReformEnumList = BIProductReformEnum.getBIProductReformEnumByBus(mainBuesineesType);
                for (BIProductReformEnum biProductReformEnum : biProductReformEnumList) {
                    PaasFormEntity shouldInsertFormEntity = new PaasFormEntity();
                    shouldInsertFormEntity.setSubProductMainFormId(paasFormEntity.getId());
                    shouldInsertFormEntity.setSubProductType(biProductReformEnum.getType());
                    shouldInsertFormEntity.setDistributorMark(paasFormEntity.getDistributorMark());
                    //产品子表单的名称就直接产品（主业务），正常其实是需要再去表单解释那边再查询一下。但是后面这边的产品子表单的名称其实是用不到的，所以构建一个差不多的产品子表单的名称
                    shouldInsertFormEntity.setName("产品（" + XbbRefTypeEnum.getByCode(biProductReformEnum.getBusinessType()).getName() + "）");
                    getSubProductPaasForm(paasFormEntity, shouldInsertFormEntity, biProductReformEnum.getSubProductBusinessType(), appCorpidMap);
                    shouldInsertFormEntity.setSort(0);
                    shouldInsertFormList.add(shouldInsertFormEntity);
                }
            }
        }
        //批量插入产品子表单表单
        if (CollectionsUtil.isNotEmpty(shouldInsertFormList)) {
            insertBatch(shouldInsertFormList);
        }
        //批量插入完产品子表单之后，需要往tb_paas_form_ref中插入产品子表单和主业务的关系
        List<PaasFormRefEntity> shouldInsertPaasFormRefList = new ArrayList<>();
        for (PaasFormEntity paasFormEntity : shouldInsertFormList) {
            Long subProductMainFormId = paasFormEntity.getSubProductMainFormId();
            Integer mainBusinessType = mainFormIdAndBusinessMap.get(subProductMainFormId);
            PaasFormRefEntity paasFormRefEntity = new PaasFormRefEntity(paasFormEntity.getCorpid(), paasFormEntity.getId(), paasFormEntity.getBusinessType(),
                    paasFormEntity.getSubProductType(), subProductMainFormId, mainBusinessType, "0", paasFormEntity.getAddTime(), paasFormEntity.getUpdateTime(),
                    BasicConstant.ZERO);
            shouldInsertPaasFormRefList.add(paasFormRefEntity);
        }
        if (CollectionsUtil.isNotEmpty(shouldInsertPaasFormRefList)) {
            paasFormRefModel.insertBatch(shouldInsertPaasFormRefList);
        }
    }

    /**
     * 获取需要保存的产品子表单
     *
     * @return
     */
    private PaasFormEntity getSubProductPaasForm(PaasFormEntity mainBusPaasForm, PaasFormEntity shouldInsertFormEntity,
                                                 Integer subProductBusinessType, Map<String, Long> appCorpidMap) {
        String corpid = mainBusPaasForm.getCorpid();
        Long productAppId = appCorpidMap.get(corpid);
        shouldInsertFormEntity.setCorpid(corpid);
        shouldInsertFormEntity.setAppId(productAppId);
        shouldInsertFormEntity.setMenuId(0L);
        shouldInsertFormEntity.setEnable(BasicConstant.ONE);
        shouldInsertFormEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
        shouldInsertFormEntity.setBusinessType(subProductBusinessType);
        shouldInsertFormEntity.setIsProcessForm(BasicConstant.ZERO);
        shouldInsertFormEntity.setVerifyRule("");
        shouldInsertFormEntity.setDisableFieldAssign(BasicConstant.TWO);
        shouldInsertFormEntity.setFrontCache(BasicConstant.ZERO);
        shouldInsertFormEntity.setTitleType(BasicConstant.ONE);
        shouldInsertFormEntity.setCustomTitle(JSONObject.toJSONString(new ArrayList<>()));
        shouldInsertFormEntity.setSummary(JSONObject.toJSONString(new ArrayList<SummaryDataPoJo>()));
        shouldInsertFormEntity.setLabels(JSONObject.toJSONString(new ArrayList<SummaryDataPoJo>()));
        shouldInsertFormEntity.setAssociationList(JSONObject.toJSONString(new ArrayList<LinkListPojo>()));
        shouldInsertFormEntity.setBusinessRules(JSONObject.toJSONString(new ArrayList<>()));
        shouldInsertFormEntity.setCoOpPerms(JSONObject.toJSONString(new CoOpPermsAddDTO()));
        long now = DateUtil.getInt();
        shouldInsertFormEntity.setCreatorId("0");
        shouldInsertFormEntity.setAddTime(now);
        shouldInsertFormEntity.setUpdateTime(now);
        shouldInsertFormEntity.setHidden(0);
        shouldInsertFormEntity.setSubProductMainFormId(mainBusPaasForm.getId());
        return shouldInsertFormEntity;
    }

    @Override
    public List<PaasFormEntityExt> getByPermission(String corpid, Integer businessType, UserVO userVO) {

        Map<String, Object> map = new HashMap<>(BasicConstant.THREE);
        map.put(StringConstant.CORPID, corpid);
        map.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        map.put("enable", 1);
        map.put(StringConstant.BUSINESS_TYPE, businessType);
        map.put("orderByStrGroup", "sort asc");

        List<PaasFormEntityExt> list = findEntitys(map);
        Iterator<PaasFormEntityExt> iterator = list.iterator();
        while (iterator.hasNext()) {
            PaasFormEntityExt paasFormEntityExt = iterator.next();
            boolean has = validatePermission(paasFormEntityExt, userVO);
            if (!has) {
                iterator.remove();
            }
        }
        return list;
    }
}
